﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using CivilRegistry.ControlledModel;
using CivilRegistry.UserControls;
using System.IO;
using CivilRegistry.Common;

namespace CivilRegistry
{
    public partial class ControlPanel : System.Web.UI.Page
    {
        ControlledModel.SuperAdmin loggedInUser = null;

        protected void Page_Load(object sender, EventArgs e)
        {
            if (SessionHandler.CurrentSession.User == null)
            {
                Response.Redirect("~/Login.aspx?&redirect=ControlPanel.aspx");
            }

            SiteMaster masterPage = (SiteMaster)Page.Master;
            masterPage.SelectedMenu = "ControlPanel";

            this.loggedInUser = SessionHandler.CurrentSession.User as SuperAdmin;

            if (this.loggedInUser == null)
            {
                Response.Redirect("~/Default.aspx");
            }

            if (!Page.IsPostBack)
            {
                pnlDisplay.Visible = false;
            }
        }

        private void FillUserGrid()
        {
            this.FillUserGrid("UserId", SortDirection.Ascending);
        }

        private void FillUserGrid(string columnName, SortDirection sortDirection)
        {
            int pageIndex = gvUsers.PageIndex;
            gvUsers.DataSource = (from user in ControlledModel.User.FindAll(user => user is Admin || user is Hospital)
                                  select new
                                      {
                                          UserId = user.UserId,
                                          FirshtName = user.FirstName,
                                          MiddleName = user.MiddleName,
                                          LastName = user.LastName,
                                          UserType = user is Admin ? "Admin" : "Hospital"
                                      }).OrderBy(columnName, sortDirection);
            gvUsers.DataBind();
            gvUsers.PageIndex = pageIndex;
        }

        protected void gvUsers_Sorting(object sender, GridViewSortEventArgs e)
        {
            if (SessionHandler.CurrentSession.SortDirection == SortDirection.Descending)
            {
                SessionHandler.CurrentSession.SortDirection = SortDirection.Ascending;
            }
            else
            {
                SessionHandler.CurrentSession.SortDirection = SortDirection.Descending;
            }

            this.FillUserGrid(e.SortExpression, SessionHandler.CurrentSession.SortDirection);

        }

        protected void gvUsers_PageIndexChanging(object sender, GridViewPageEventArgs e)
        {
            gvUsers.PageIndex = e.NewPageIndex;
            this.FillUserGrid();
        }

        protected void gvUsers_RowCommand(object sender, GridViewCommandEventArgs e)
        {
            if (e.CommandName == "Edit")
            {
                var gvHdnUserId = (HiddenField)gvUsers.Rows[Convert.ToInt32(e.CommandArgument) - (gvUsers.PageSize * gvUsers.PageIndex)].FindControl("hdnUserId");
                var gvHdnUserType = (HiddenField)gvUsers.Rows[Convert.ToInt32(e.CommandArgument) - (gvUsers.PageSize * gvUsers.PageIndex)].FindControl("hdnUserType");

                if (gvHdnUserType.Value == "Admin")
                {
                    this.hdnUserType.Value = "Admin";
                    this.LoadUserValues(ControlledModel.Admin.FindById(Convert.ToInt32(gvHdnUserId.Value)));
                }
                else
                {
                    this.hdnUserType.Value = "Hospital";
                    this.LoadUserValues(ControlledModel.Hospital.FindById(Convert.ToInt32(gvHdnUserId.Value)));
                }

                gvUsers.Visible = false;
                pnlTools.Visible = false;
                pnlDisplay.Visible = true;
            }
        }

        protected void gvUsers_RowEditing(object sender, GridViewEditEventArgs e)
        {
            e.Cancel = true;
        }

        protected void btnCancel_Click(object sender, EventArgs e)
        {
            pnlEditUser.Visible = false;

            if (hdnUserType.Value == "")
            {
                pnlTools.Visible = true;
            }
            else
            {
                pnlDisplay.Visible = true;
            }
        }

        protected void btnEdit_Click(object sender, EventArgs e)
        {
            if (hdnUserType.Value == "Admin")
            {
                this.LoadEditUserValues(Admin.FindById(Convert.ToInt32(hdnUserId.Value)));
            }
            else
            {
                this.LoadEditUserValues(Hospital.FindById(Convert.ToInt32(hdnUserId.Value)));
            }

            lblUserType.Visible = false;
            ddlUserType.Visible = false;
            pnlDisplay.Visible = false;
            pnlTools.Visible = false;
            pnlEditUser.Visible = true;
        }

        private void LoadEditUserValues(ControlledModel.User user)
        {
            txtEmailAddress.Text = user.EmailAddress;
            txtPhoneNo.Text = user.PhoneNo.ToString();
            txtFirstName.Text = user.FirstName;
            txtMiddleName.Text = user.MiddleName;
            txtUserName.Text = user.UserName;
            txtDateofBirth.Text = user.DateOfBirth.ToString();
            ((TextBox)ucPermanentAddress.FindControl("txtAddress")).Text = user.PermanentAddress.Address;
            ((TextBox)ucPermanentAddress.FindControl("txtPIN")).Text = user.PermanentAddress.PIN.ToString();
            ((DropDownList)ucPermanentAddress.FindControl("ddlStateName")).SelectedIndex = user.PermanentAddress.District.State.StateId;
            var ddlDistrictName = ((DropDownList)ucPermanentAddress.FindControl("ddlDistrictName"));
            ddlDistrictName.DataSource = District.FindAllByStateId(user.PermanentAddress.District.State.StateId);
            ddlDistrictName.DataBind();
            ddlDistrictName.SelectedValue = user.PermanentAddress.District.DistrictId.ToString();
            ((TextBox)ucPermanentAddress.FindControl("txtCity")).Text = user.PermanentAddress.City;
        }

        private void LoadUserValues(ControlledModel.User user)
        {
            hdnUserId.Value = user.UserId.ToString();
            lblUserIdValue.Text = user.UserId.ToString();
            lblUserNameValue.Text = user.UserName;
            lblFirstNameValue.Text = user.FirstName;
            lblMiddleNameValue.Text = user.MiddleName;
            lblLastNameValue.Text = user.LastName;
            lblEmailAddressValue.Text = user.EmailAddress;
            lblPhoneNoValue.Text = user.PhoneNo.ToString();
            lblDateOfBirthValue.Text = user.DateOfBirth.ToString();
            lblAddressValue.Text = user.PermanentAddress.Address;
            lblPINValue.Text = user.PermanentAddress.PIN.ToString();
            lblCityValue.Text = user.PermanentAddress.City;
            lblStateNameValue.Text = user.PermanentAddress.District.State.StateName;
            lblDistrictNameValue.Text = user.PermanentAddress.District.DistrictName;
        }

        protected void btnSave_Click(object sender, EventArgs e)
        {
            ControlledModel.User user;

            if (((TextBox)ucPermanentAddress.FindControl("txtAddress")).Text == "")
            {
                lblStatus.Text = "Please enter the address";
                return;
            }

            if (lblUserType.Visible)
            {
                hdnUserType.Value = ddlUserType.SelectedItem.Text;

                if (ddlUserType.SelectedItem.Text == "Admin")
                {
                    user = new Admin();
                    this.FillUserDataFromUI(ref user);

                    try
                    {
                        user = this.loggedInUser.CreateUser<Admin>((Admin)user);
                    }
                    catch (ApplicationException ex)
                    {
                        lblStatus.Text = ex.Message;
                        return;
                    }
                    catch (Exception ex)
                    {
                        Logger.ErrorLogger.Log(ex);
                        lblStatus.Text = "An unexpected error occured on the application. Please contact the appropriate technical candidate for more information.";
                    }
                }
                else if (ddlUserType.SelectedItem.Text == "Hospital")
                {
                    user = new Hospital();
                    this.FillUserDataFromUI(ref user);

                    try
                    {
                        user = this.loggedInUser.CreateUser<Hospital>((Hospital)user);
                    }
                    catch (ApplicationException ex)
                    {
                        lblStatus.Text = ex.Message;
                        return;
                    }
                    catch (Exception ex)
                    {
                        Logger.ErrorLogger.Log(ex);
                        lblStatus.Text = "An unexpected error occured on the application. Please contact the appropriate technical candidate for more information.";
                    }
                }
                else
                {
                    lblStatus.Text = "Please select the user type.";
                    return;
                }
            }
            else
            {
                if (hdnUserType.Value == "Admin")
                {
                    user = Admin.FindById(Convert.ToInt32(hdnUserId.Value));
                    this.FillUserDataFromUI(ref user);
                }
                else
                {
                    user = Hospital.FindById(Convert.ToInt32(hdnUserId.Value));
                    this.FillUserDataFromUI(ref user);
                }

                try
                {
                    user = this.loggedInUser.Modify(user);
                }
                catch (ApplicationException ex)
                {
                    lblStatus.Text = ex.Message;
                    return;
                }
                catch (Exception ex)
                {
                    Logger.ErrorLogger.Log(ex);
                    lblStatus.Text = "An unexpected error occured on the application. Please contact the appropriate technical candidate for more information.";
                }
            }

            FileUpload electricityBillUploader = ((FileUpload)ucPermanentAddress.FindControl("FlupldElectricitybill"));
            if (electricityBillUploader.PostedFile.FileName != "")
            {
                if (electricityBillUploader.PostedFile.FileName.ToLowerInvariant().EndsWith(".pdf"))
                {
                    electricityBillUploader.SaveAs(user.GetPermanentAddressElectricalBillFilePath());
                }
                else
                {
                    lblStatus.Text = "Please upload a valid file. Note: The file should be in pdf format.";
                    return;
                }
            }

            lblStatus.Text = "Changes saved successfully.";

            if (lblUserType.Visible)
            {
                EmailHelper.SendPassword(user, ref lblStatus);
            }

            if (hdnUserType.Value == "Admin")
            {
                this.LoadUserValues(ControlledModel.Admin.FindById(user.UserId));
            }
            else
            {
                 this.LoadUserValues(ControlledModel.Hospital.FindById(user.UserId));
            }

            pnlDisplay.Visible = true;
            pnlEditUser.Visible = false;
        }

        private void FillUserDataFromUI(ref ControlledModel.User user)
        {
            user.UserName = txtUserName.Text;
            user.FirstName = txtFirstName.Text;
            user.MiddleName = txtMiddleName.Text;
            user.EmailAddress = txtEmailAddress.Text;
            user.PhoneNo = Convert.ToInt64(txtPhoneNo.Text);
            user.DateOfBirth = Convert.ToDateTime(txtDateofBirth.Text);

            var permanentAddress = new PermanentAddress();
            permanentAddress.Address = ((TextBox)ucPermanentAddress.FindControl("txtAddress")).Text;
            permanentAddress.PIN = (Convert.ToInt32(((TextBox)ucPermanentAddress.FindControl("txtPIN")).Text));
            permanentAddress.District = District.FindById(Convert.ToInt32(((DropDownList)ucPermanentAddress.FindControl("ddlDistrictName")).SelectedValue));
            permanentAddress.District.State = State.FindById(Convert.ToInt32(((DropDownList)ucPermanentAddress.FindControl("ddlStateName")).SelectedValue));
            permanentAddress.City = ((TextBox)ucPermanentAddress.FindControl("txtCity")).Text;

            user.PermanentAddress = permanentAddress;
        }

        protected void btnViewAll_Click(object sender, EventArgs e)
        {
            this.FillUserGrid();
            pnlTools.Visible = false;
        }

        protected void btnAddUser_Click(object sender, EventArgs e)
        {
            pnlDisplay.Visible = false;
            pnlTools.Visible = false;
            pnlEditUser.Visible = true;
        }

    }
}